package org.jeecg.modules.business.warehouse.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.basic.customer.service.IBasicCustomerService;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseAreaLocation;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaLocationService;
import org.jeecg.modules.basic.warehouseGroup.mapper.WmsBasicWarehouseGroupUserMapper;
import org.jeecg.modules.business.doc.business.entity.WmsInReceipt;
import org.jeecg.modules.business.doc.business.entity.WmsInReceiptMaterial;
import org.jeecg.modules.business.doc.business.mapper.WmsInReceiptMapper;
import org.jeecg.modules.business.doc.business.mapper.WmsInReceiptMaterialMapper;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptService;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceipt;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceiptMaterial;
import org.jeecg.modules.business.doc.outbound.mapper.WmsOutReceiptMapper;
import org.jeecg.modules.business.doc.outbound.mapper.WmsOutReceiptMaterialMapper;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.entity.vo.RepertorySimpleVO;
import org.jeecg.modules.business.outbound.mapper.WmsOutReceiptTaskMapper;
import org.jeecg.modules.business.outbound.mapper.WmsOutReceiptTaskMaterialMapper;
import org.jeecg.modules.business.repertory.entity.WmsTaskMaterialLight;
import org.jeecg.modules.business.repertory.service.IWmsTaskMaterialLightService;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlan;
import org.jeecg.modules.business.takestockplan.mapper.TakeStockPlanMapper;
import org.jeecg.modules.business.warehouse.entity.*;
import org.jeecg.modules.business.warehouse.entity.vo.*;
import org.jeecg.modules.business.warehouse.mapper.WmsInReceiptTaskMapper;
import org.jeecg.modules.business.warehouse.mapper.WmsInReceiptTaskMaterialMapper;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskService;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.entity.DockDataReceiveRecord;
import org.jeecg.modules.dock.entity.WmsLightConfig;
import org.jeecg.modules.dock.entity.light.request.LightRequestVO;
import org.jeecg.modules.dock.enums.LightStateEnum;
import org.jeecg.modules.dock.service.IWmsLightConfigService;
import org.jeecg.modules.dock.service.LightIBSDockingService;
import org.jeecg.modules.flow.callback.enums.NeedTransferDocumentTypeEnum;
import org.jeecg.modules.flow.callback.enums.SimpleDocumentTypeEnum;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 入库任务
 * @Author: jeecg-boot
 * @Date: 2023-07-28
 * @Version: V1.0
 */
@Service
@Slf4j
public class WmsInReceiptTaskServiceImpl extends ServiceImpl<WmsInReceiptTaskMapper, WmsInReceiptTask> implements IWmsInReceiptTaskService {

    private static final String hasSave = "1";
    @Resource
    private WmsInReceiptTaskMapper wmsInReceiptTaskMapper;
    @Resource
    private WmsInReceiptTaskMaterialMapper wmsInReceiptTaskMaterialMapper;
    @Resource
    private WmsInReceiptMapper wmsInReceiptMapper;
    @Resource
    private WmsInReceiptMaterialMapper wmsInReceiptMaterialMapper;
    @Resource
    private WmsOutReceiptTaskMapper wmsOutReceiptTaskMapper;
    @Resource
    private WmsOutReceiptTaskMaterialMapper wmsOutReceiptTaskMaterialMapper;
    @Resource
    private WmsOutReceiptMapper wmsOutReceiptMapper;
    @Resource
    private WmsOutReceiptMaterialMapper wmsOutReceiptMaterialMapper;
    @Resource
    private TakeStockPlanMapper takeStockPlanMapper;
    @Autowired
    private IBasicMaterialService iBasicMaterialService;
    @Autowired
    private IBasicCustomerService customerService;
    @Lazy
    @Resource
    private IWmsInReceiptService wmsInReceiptService;
    @Resource
    private WmsBasicWarehouseGroupUserMapper wmsBasicWarehouseGroupUserMapper;
    @Autowired
    private IWmsTaskMaterialLightService iWmsTaskMaterialLightService;
    @Autowired
    private IWmsLightConfigService iWmsLightConfigService;
    @Autowired
    private LightIBSDockingService lightIBSDockingService;
    @Autowired
    private IWmsBasicWarehouseAreaLocationService iWmsBasicWarehouseAreaLocationService;

    @Value("${wms.config.light.mode:simulate}")
    private String lightMode;

    private final String[] needHandleLight = {"R12","R14","R101"};

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveMain(WmsInReceiptTask wmsInReceiptTask, List<WmsInReceiptTaskMaterial> wmsInReceiptTaskMaterialList) {
        //将物料、批次、钢卷号、仓库、库区、库位相同的合并为一条
        wmsInReceiptTaskMaterialList = operateMaterialList(wmsInReceiptTaskMaterialList);
        if (StrUtil.isBlank(wmsInReceiptTask.getRequestPerson())) {
            wmsInReceiptTask.setRequestPerson("WMS请求人员");
        }
        //2023/12/08产品让改为-自建任务来源系统为空
//        if (StrUtil.isBlank(wmsInReceiptTask.getOriginalSystem())){
//            wmsInReceiptTask.setOriginalSystem("WMS");
//        }
        //设置过账状态
        TransferStatusEnum transferStatus = getTransferStatusWhenSave(SimpleDocumentTypeEnum.IN_TASK, wmsInReceiptTask.getDocumentType());
        wmsInReceiptTask.setTransferSapStatus(transferStatus.getCode());
        wmsInReceiptTaskMapper.insert(wmsInReceiptTask);
        if (wmsInReceiptTaskMaterialList != null && wmsInReceiptTaskMaterialList.size() > 0) {
            int i = 1;
            for (WmsInReceiptTaskMaterial entity : wmsInReceiptTaskMaterialList) {
                //外键设置
                entity.setWmsInReceiptTaskId(wmsInReceiptTask.getId());
                entity.setUnwarehousedQuantity(entity.getPlanQuantity());
                entity.setInspectStatus(InspectStatusEnum.NOT_INSPECT.getName());
                entity.setIncomingQuality("false");
                entity.setUnInspectCanPut("false");
                setMaterialUnitIfEmpty(entity);
                BasicMaterial basicMaterial = iBasicMaterialService.getById(entity.getWmsBasicMaterialId());
                if (basicMaterial == null) {
                    log.error("物料id:{} 未找到物料信息", entity.getWmsBasicMaterialId());
                    throw new JeecgBootException("物料id:" + entity.getWmsBasicMaterialId() + " 未找到物料信息");
                }
                String inspect = basicMaterial.getInspect();
                if (StringUtils.isNotBlank(inspect)) {
                    if (inspect.contains("1")) {
                        entity.setIncomingQuality("true");
                        entity.setInspectStatus(InspectStatusEnum.WAIT_INSPECT.getName());
                    }
                    if (inspect.contains("3")) {
                        entity.setUnInspectCanPut("true");
                    }
                }
                //更新序号
                if (StrUtil.isBlank(entity.getUpstreamLineNumber())) {
                    entity.setUpstreamLineNumber(String.valueOf(i));
                    i++;
                }
                wmsInReceiptTaskMaterialMapper.insert(entity);
                //更新是否使用
                iBasicMaterialService.updateUsedState(entity.getWmsBasicMaterialId());
            }
        }
        customerService.updateUsed(wmsInReceiptTask.getWmsBasicSupplierId());
        return wmsInReceiptTask.getId();
    }

    void setMaterialUnitIfEmpty(WmsInReceiptTaskMaterial wmsInReceiptTaskMaterial) {
        BasicMaterial material = iBasicMaterialService.getById(wmsInReceiptTaskMaterial.getWmsBasicMaterialId());
        if (ObjectUtil.isNotNull(material)) {
            if (StrUtil.isEmpty(wmsInReceiptTaskMaterial.getWmsBasicUnitId())) {
                wmsInReceiptTaskMaterial.setWmsBasicUnitId(material.getInventoryUnitId());
            }
            if (StrUtil.isEmpty(wmsInReceiptTaskMaterial.getUnitAssistId())) {
                wmsInReceiptTaskMaterial.setUnitAssistId(material.getAssistantUnitId());
            }
        }
    }

    /**
     * 如果存在物料、批次、钢卷号、仓库、库区、库位相同的,合并成一条数据,加一下数量
     */
    List<WmsInReceiptTaskMaterial> operateMaterialList(List<WmsInReceiptTaskMaterial> list) {
        //物料、批次、钢卷号、仓库、库区、库位进行分组
        Map<String, List<WmsInReceiptTaskMaterial>> collect = list.stream().collect(Collectors.groupingBy(o ->
                        o.getWmsBasicMaterialId() + "-"
                                + o.getBatchCode() + "-"
                                + o.getSteelCoilNumber() + "-"
                                + o.getWmsBasicWarehouseId() + "-"
                                + o.getWmsBasicWarehouseAreaId() + "-"
                                + o.getWmsBasicWarehouseAreaLocationId()
                )
        );
        List<WmsInReceiptTaskMaterial> res = new ArrayList<>();
        collect.forEach((key, value) -> {
            if (CollectionUtil.isNotEmpty(value)) {
                //物料、批次、钢卷号、仓库、库区、库位相同的出现多条,合并为一条,把数量加一下(planQuantity、assistQuantity)
                WmsInReceiptTaskMaterial taskMaterial = value.get(0);
                if (value.size() > 1) {
                    BigDecimal sumPlanQuantity = value.stream().map(WmsInReceiptTaskMaterial::getPlanQuantity)
                            .filter(ObjectUtil::isNotNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal sumAssistQuantity = value.stream().map(WmsInReceiptTaskMaterial::getAssistQuantity)
                            .filter(ObjectUtil::isNotNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    if (sumPlanQuantity.compareTo(BigDecimal.ZERO) > 0) {
                        taskMaterial.setPlanQuantity(sumPlanQuantity);
                    }
                    if (sumAssistQuantity.compareTo(BigDecimal.ZERO) > 0) {
                        taskMaterial.setAssistQuantity(sumAssistQuantity);
                    }
                }
                res.add(taskMaterial);
            }
        });
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(WmsInReceiptTask wmsInReceiptTask, List<WmsInReceiptTaskMaterial> wmsInReceiptTaskMaterialList) {
        wmsInReceiptTaskMapper.updateById(wmsInReceiptTask);

        List<WmsInReceiptTaskMaterial> taskMaterials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, wmsInReceiptTask.getId()));
        //1.先删除子表数据
        wmsInReceiptTaskMaterialMapper.deleteByMainId(wmsInReceiptTask.getId());

        for (WmsInReceiptTaskMaterial taskMaterial : taskMaterials) {
            //更新是否使用
            iBasicMaterialService.updateUsedState(taskMaterial.getWmsBasicMaterialId());
        }
        customerService.updateUsed(wmsInReceiptTask.getWmsBasicSupplierId());

        //2.子表数据重新插入
        if (wmsInReceiptTaskMaterialList != null && wmsInReceiptTaskMaterialList.size() > 0) {
            for (WmsInReceiptTaskMaterial entity : wmsInReceiptTaskMaterialList) {
                //外键设置
                entity.setWmsInReceiptTaskId(wmsInReceiptTask.getId());
                entity.setUnwarehousedQuantity(entity.getPlanQuantity());
                wmsInReceiptTaskMaterialMapper.insert(entity);
                //更新是否使用
                iBasicMaterialService.updateUsedState(entity.getWmsBasicMaterialId());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        WmsInReceiptTask task = wmsInReceiptTaskMapper.selectById(id);
        if (!task.getDocumentStatus().equals(hasSave)) {
            throw new JeecgBootException("当前单据状态非已保存，不可删除");
        }
        List<WmsInReceiptTaskMaterial> taskMaterials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, task.getId()));
        wmsInReceiptTaskMaterialMapper.deleteByMainId(id);
        wmsInReceiptTaskMapper.deleteById(id);

        for (WmsInReceiptTaskMaterial taskMaterial : taskMaterials) {
            //更新是否使用
            iBasicMaterialService.updateUsedState(taskMaterial.getWmsBasicMaterialId());
        }
        customerService.updateUsed(task.getWmsBasicSupplierId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        List<WmsInReceiptTask> inReceiptTasks = wmsInReceiptTaskMapper.selectBatchIds(idList);
        List<String> collect = inReceiptTasks.stream().map(WmsInReceiptTask::getDocumentStatus).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(collect)) {
            if (collect.contains("200")) {
                throw new JeecgBootException("所选数据包含已完成的入库单,请重新选择");
            }
        }

        List<String> ids = inReceiptTasks.stream().map(WmsInReceiptTask::getId).collect(Collectors.toList());
        List<WmsInReceiptTaskMaterial> taskMaterials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                .in(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, ids));

        for (Serializable id : idList) {
            wmsInReceiptTaskMaterialMapper.deleteByMainId(id.toString());
            wmsInReceiptTaskMapper.deleteById(id);
        }

        for (WmsInReceiptTaskMaterial taskMaterial : taskMaterials) {
            //更新是否使用
            iBasicMaterialService.updateUsedState(taskMaterial.getWmsBasicMaterialId());
        }
        for (WmsInReceiptTask inReceiptTask : inReceiptTasks) {
            customerService.updateUsed(inReceiptTask.getWmsBasicSupplierId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void commitOrCancelCommit(String wmsInReceiptTaskId, Integer documentStatus) {
        //提交请求
        if (documentStatus.equals(1)) {
            List<WmsInReceiptTaskMaterial> list = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                    .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, wmsInReceiptTaskId));
            if (CollectionUtil.isEmpty(list)) {
                throw new JeecgBootException("当前入库任务无物料明细，无法提交");
            }
            WmsInReceiptTask task = wmsInReceiptTaskMapper.selectById(wmsInReceiptTaskId);
            task.setDocumentStatus("已提交");
            wmsInReceiptTaskMapper.updateById(task);
        } else {
            List<WmsInReceipt> wmsInReceipts = wmsInReceiptMapper.selectList(new LambdaQueryWrapper<WmsInReceipt>()
                    .eq(WmsInReceipt::getWmsInReceiptTaskId, wmsInReceiptTaskId));
            if (CollectionUtil.isNotEmpty(wmsInReceipts)) {
                throw new JeecgBootException("当前单据已产生下游单据，不可撤销提交");
            }
            WmsInReceiptTask task = wmsInReceiptTaskMapper.selectById(wmsInReceiptTaskId);
            task.setDocumentStatus("已保存");
            wmsInReceiptTaskMapper.updateById(task);
        }
    }

    @Override
    public void updateStatus(String id, Integer taskType) {
        //入库任务
        if (taskType.equals(1)) {
            boolean result = true;
            WmsInReceipt wmsInReceipt = wmsInReceiptMapper.selectById(id);
            if (ObjectUtil.isNotEmpty(wmsInReceipt)) {
                //入库任务id
                String taskId = wmsInReceipt.getWmsInReceiptTaskId();
                if (StrUtil.isEmpty(taskId)) {
                    throw new JeecgBootException("入库单没有任务！");
                }
                //入库任务-物料
                List<WmsInReceiptTaskMaterial> list = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, taskId));
                if (ObjectUtil.isEmpty(list)) {
                    throw new JeecgBootException("入库任务无物料明细！");
                }
                WmsInReceiptTask task = wmsInReceiptTaskMapper.selectById(taskId);
                for (WmsInReceiptTaskMaterial taskMaterial : list) {
                    LambdaQueryWrapper<WmsInReceiptMaterial> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WmsInReceiptMaterial::getWmsInReceiptId, id);
                    queryWrapper.eq(WmsInReceiptMaterial::getWmsBasicMaterialId, taskMaterial.getWmsBasicMaterialId());
                    if (StrUtil.isNotBlank(taskMaterial.getBatchCode())) {
                        queryWrapper.eq(WmsInReceiptMaterial::getBatchCode, taskMaterial.getBatchCode());
                    }
                    List<WmsInReceiptMaterial> realMaterialList = wmsInReceiptMaterialMapper.selectList(queryWrapper);
                    if (ObjectUtil.isEmpty(realMaterialList)) {
                        //如果入库单没有这种物料，不更新已入库数量和未入库数量
//                        taskMaterial.setWarehousedQuantity(BigDecimal.ZERO);
//                        taskMaterial.setUnwarehousedQuantity(taskMaterial.getPlanQuantity());
//                        wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                    } else {
                        //如果有这种物料，则比对任务数量和实际入库数量
                        WmsInReceiptMaterial real = realMaterialList.get(0);
                        //获取未入库数量
                        BigDecimal unwarehousedQuantity = taskMaterial.getUnwarehousedQuantity();
                        if (ObjectUtil.isEmpty(unwarehousedQuantity)) {
                            //如果未入库数量为空，默认为计划入库数量
                            unwarehousedQuantity = taskMaterial.getPlanQuantity();
                        }
                        if (unwarehousedQuantity.compareTo(real.getWarehouseQuantity()) > 0) {
                            //获取已入库数量
                            BigDecimal taskOutbount = ObjectUtil.isEmpty(taskMaterial.getWarehousedQuantity()) ? BigDecimal.ZERO : taskMaterial.getWarehousedQuantity();
                            taskMaterial.setWarehousedQuantity(taskOutbount.add(real.getWarehouseQuantity()));
                            taskMaterial.setUnwarehousedQuantity(unwarehousedQuantity.subtract(real.getWarehouseQuantity()));
                            taskMaterial.setWarehouseStatus("2");
                            wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                            result = false;
                        } else if (unwarehousedQuantity.compareTo(real.getWarehouseQuantity()) == 0) {
                            taskMaterial.setWarehousedQuantity(taskMaterial.getPlanQuantity());
                            taskMaterial.setUnwarehousedQuantity(BigDecimal.ZERO);
                            taskMaterial.setWarehouseStatus("3");
                            wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                        } else {
                            //这种物料超计划入库
                            BigDecimal taskOutbount = ObjectUtil.isEmpty(taskMaterial.getWarehousedQuantity()) ? BigDecimal.ZERO : taskMaterial.getWarehousedQuantity();
                            taskMaterial.setWarehousedQuantity(taskOutbount.add(real.getWarehouseQuantity()));
                            taskMaterial.setUnwarehousedQuantity(BigDecimal.ZERO);
                            taskMaterial.setWarehouseStatus("3");
                            wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                        }
                    }
                }
                //判断任务的状态--如果任务的所有物料未入库数量都为0，则判定任务完成
                //重新获取入库任务-物料
                List<WmsInReceiptTaskMaterial> newList = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, taskId));
                int num = 0;
                for (WmsInReceiptTaskMaterial newTask : newList) {
                    if (newTask.getUnwarehousedQuantity().compareTo(BigDecimal.ZERO) == 0) {
                        num++;
                    }
                }
                if (num < newList.size()) {
                    result = false;
                }
                if (!result) {
                    task.setWarehouseStatus("2");
                } else {
                    task.setWarehouseStatus("3");
                    task.setDocumentStatus("200");
                }
                wmsInReceiptTaskMapper.updateById(task);
            } else {
                throw new JeecgBootException("入库单不存在!");
            }
        } else if (taskType.equals(2)) {
            boolean result = true;
            WmsOutReceipt wmsOutReceipt = wmsOutReceiptMapper.selectById(id);
            if (ObjectUtil.isNotEmpty(wmsOutReceipt)) {
                //出库任务id
                String taskId = wmsOutReceipt.getWmsOutReceiptTaskId();
//                if (StrUtil.isEmpty(taskId)) {
//                    throw new JeecgBootException("出库单没有任务！");
//                }
                //出库任务-物料
                List<WmsOutReceiptTaskMaterial> list = wmsOutReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsOutReceiptTaskMaterial>()
                        .eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId, taskId));
                if (ObjectUtil.isEmpty(list)) {
                    throw new JeecgBootException("出库任务无物料明细！");
                }
                WmsOutReceiptTask task = wmsOutReceiptTaskMapper.selectById(taskId);
                for (WmsOutReceiptTaskMaterial taskMaterial : list) {
                    LambdaQueryWrapper<WmsOutReceiptMaterial> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WmsOutReceiptMaterial::getWmsOutReceiptId, id);
                    queryWrapper.eq(WmsOutReceiptMaterial::getWmsBasicMaterialId, taskMaterial.getWmsBasicMaterialId());
                    if (StrUtil.isNotBlank(taskMaterial.getBatchCode())) {
                        queryWrapper.eq(WmsOutReceiptMaterial::getBatchCode, taskMaterial.getBatchCode());
                    }
                    List<WmsOutReceiptMaterial> realMaterialList = wmsOutReceiptMaterialMapper.selectList(queryWrapper);
                    if (ObjectUtil.isEmpty(realMaterialList)) {
                        //如果出库单没有这种物料，则已出库数量为0，未出库数量=计划出库数量
//                        taskMaterial.setOutboundQuantity(BigDecimal.ZERO);
//                        taskMaterial.setUnoutboundQuantity(taskMaterial.getPlanQuantity());
//                        wmsOutReceiptTaskMaterialMapper.updateById(taskMaterial);
                    } else {
                        //如果有这种物料，则比对任务数量和实际出库数量
                        WmsOutReceiptMaterial real = realMaterialList.get(0);
                        //获取未出库数量
                        BigDecimal unoutboundQuantity = taskMaterial.getUnoutboundQuantity();
                        if (ObjectUtil.isEmpty(unoutboundQuantity)) {
                            //如果未出库数量为空，默认为计划出库数量
                            unoutboundQuantity = taskMaterial.getPlanQuantity();
                        }
                        if (unoutboundQuantity.compareTo(real.getOutboundQuantity()) > 0) {
                            //获取已出库数量
                            BigDecimal taskOutbount = ObjectUtil.isEmpty(taskMaterial.getHasOutboundQuantity()) ? BigDecimal.ZERO : taskMaterial.getHasOutboundQuantity();
                            taskMaterial.setHasOutboundQuantity(taskOutbount.add(real.getOutboundQuantity()));
                            taskMaterial.setUnoutboundQuantity(unoutboundQuantity.subtract(real.getOutboundQuantity()));
                            taskMaterial.setOutboundStatus("2");
                            wmsOutReceiptTaskMaterialMapper.updateById(taskMaterial);
                            result = false;
                        } else if (unoutboundQuantity.compareTo(real.getOutboundQuantity()) == 0) {
                            taskMaterial.setHasOutboundQuantity(taskMaterial.getPlanQuantity());
                            taskMaterial.setUnoutboundQuantity(BigDecimal.ZERO);
                            taskMaterial.setOutboundStatus("3");
                            wmsOutReceiptTaskMaterialMapper.updateById(taskMaterial);
                        } else {
                            //这种物料超计划出库
                            BigDecimal taskOutbount = ObjectUtil.isEmpty(taskMaterial.getHasOutboundQuantity()) ? BigDecimal.ZERO : taskMaterial.getHasOutboundQuantity();
                            taskMaterial.setHasOutboundQuantity(taskOutbount.add(real.getOutboundQuantity()));
                            taskMaterial.setUnoutboundQuantity(BigDecimal.ZERO);
                            taskMaterial.setOutboundStatus("3");
                            wmsOutReceiptTaskMaterialMapper.updateById(taskMaterial);
                        }
                    }
                }
                //重新获取出库任务-物料
                List<WmsOutReceiptTaskMaterial> newList = wmsOutReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsOutReceiptTaskMaterial>()
                        .eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId, taskId));
                int num = 0;
                for (WmsOutReceiptTaskMaterial newTask : newList) {
                    if (newTask.getUnoutboundQuantity().compareTo(BigDecimal.ZERO) == 0) {
                        num++;
                    }
                }
                if (num < list.size()) {
                    result = false;
                }
                if (!result) {
                    task.setOutboundStatus("2");
                } else {
                    task.setOutboundStatus("3");
                    task.setDocumentStatus("200");
                }
                wmsOutReceiptTaskMapper.updateById(task);
            } else {
                throw new JeecgBootException("出库单不存在!");
            }
        } else {
            throw new JeecgBootException("错误的任务类型！");
        }
    }

    @Override
    public void updateReceipt(String id) {
        boolean result = true;
        WmsInReceipt wmsInReceipt = wmsInReceiptMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(wmsInReceipt)) {
            //入库任务id
            String taskId = wmsInReceipt.getWmsInReceiptTaskId();
            if (StrUtil.isNotEmpty(taskId)) {
                //入库任务-物料
                List<WmsInReceiptTaskMaterial> list = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, taskId));
                if (ObjectUtil.isEmpty(list)) {
                    throw new JeecgBootException("入库任务无物料明细！");
                }
                WmsInReceiptTask task = wmsInReceiptTaskMapper.selectById(taskId);
                for (WmsInReceiptTaskMaterial taskMaterial : list) {
                    LambdaQueryWrapper<WmsInReceiptMaterial> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WmsInReceiptMaterial::getWmsInReceiptId, id);
                    queryWrapper.eq(WmsInReceiptMaterial::getWmsBasicMaterialId, taskMaterial.getWmsBasicMaterialId());
                    if (StrUtil.isNotBlank(taskMaterial.getBatchCode())) {
                        queryWrapper.eq(WmsInReceiptMaterial::getBatchCode, taskMaterial.getBatchCode());
                    }
                    if (StrUtil.isNotBlank(taskMaterial.getOriginalSystemLineNumber())) {
                        queryWrapper.eq(WmsInReceiptMaterial::getOriginalSystemLineNumber, taskMaterial.getOriginalSystemLineNumber());
                    }
                    if (StrUtil.isNotBlank(taskMaterial.getOriginalSystemNumber())) {
                        queryWrapper.eq(WmsInReceiptMaterial::getOriginalSystemNumber, taskMaterial.getOriginalSystemNumber());
                    }
                    List<WmsInReceiptMaterial> realMaterialList = wmsInReceiptMaterialMapper.selectList(queryWrapper);
                    if (ObjectUtil.isEmpty(realMaterialList)) {
                        //如果入库单没有这种物料，不更新已入库数量和未入库数量
//                        taskMaterial.setWarehousedQuantity(BigDecimal.ZERO);
//                        taskMaterial.setUnwarehousedQuantity(taskMaterial.getPlanQuantity());
//                        wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                    } else {
                        //如果有这种物料，则比对任务数量和实际入库数量
                        WmsInReceiptMaterial real = realMaterialList.get(0);
                        //获取未入库数量
                        BigDecimal unwarehousedQuantity = taskMaterial.getUnwarehousedQuantity();
                        if (unwarehousedQuantity == null) {
                            throw new JeecgBootException("该入库单关联的入库任务物料的计划数量是空！");
                        }
                        BigDecimal unwarehousedQuantityAssit = taskMaterial.getUnwarehousedQuantityAssist();
                        if (ObjectUtil.isEmpty(unwarehousedQuantity)) {
                            //如果未入库数量为空，默认为计划入库数量
                            unwarehousedQuantity = taskMaterial.getPlanQuantity();
                        }
                        if (ObjectUtil.isEmpty(unwarehousedQuantityAssit)) {
                            //如果未入库数量(辅数量)为空，默认为计划入库数量(辅数量)
                            unwarehousedQuantityAssit = taskMaterial.getAssistQuantity();
                        }
                        if (ObjectUtil.isNull(real.getWarehouseQuantity())) {
                            real.setWarehouseQuantity(BigDecimal.ZERO);
                        }
                        if (unwarehousedQuantity.compareTo(real.getWarehouseQuantity()) > 0) {
                            //获取已入库数量
                            BigDecimal taskOutbount = ObjectUtil.isEmpty(taskMaterial.getWarehousedQuantity()) ? BigDecimal.ZERO : taskMaterial.getWarehousedQuantity();
                            taskMaterial.setWarehousedQuantity(taskOutbount.add(real.getWarehouseQuantity()));
                            taskMaterial.setUnwarehousedQuantity(unwarehousedQuantity.subtract(real.getWarehouseQuantity()));
                            //获取已入库数量(辅数量)
                            BigDecimal taskOutbountAssit = ObjectUtil.isEmpty(taskMaterial.getWarehousedQuantityAssist()) ? BigDecimal.ZERO : taskMaterial.getWarehousedQuantityAssist();
                            taskMaterial.setWarehousedQuantityAssist(taskOutbountAssit.add(ObjectUtil.isNull(real.getAssistQuantity()) ? BigDecimal.ZERO : real.getAssistQuantity()));
                            if (ObjectUtil.isNotNull(unwarehousedQuantityAssit)) {
                                taskMaterial.setUnwarehousedQuantityAssist(unwarehousedQuantityAssit.subtract(ObjectUtil.isNull(real.getWarehouseQuantityAssist()) ? BigDecimal.ZERO : real.getWarehouseQuantityAssist()));
                            }
                            taskMaterial.setWarehouseStatus("2");
                            wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                            result = false;
                        } else if (unwarehousedQuantity.compareTo(real.getWarehouseQuantity()) == 0) {
                            taskMaterial.setWarehousedQuantity(taskMaterial.getPlanQuantity());
                            taskMaterial.setUnwarehousedQuantity(BigDecimal.ZERO);
                            taskMaterial.setWarehousedQuantityAssist(taskMaterial.getAssistQuantity());
                            taskMaterial.setUnwarehousedQuantityAssist(BigDecimal.ZERO);
                            taskMaterial.setWarehouseStatus("3");
                            wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                        } else {
                            //这种物料超计划入库
                            BigDecimal taskOutbount = ObjectUtil.isEmpty(taskMaterial.getWarehousedQuantity()) ? BigDecimal.ZERO : taskMaterial.getWarehousedQuantity();
                            taskMaterial.setWarehousedQuantity(taskOutbount.add(real.getWarehouseQuantity()));
                            taskMaterial.setUnwarehousedQuantity(BigDecimal.ZERO);
                            //获取已入库数量(辅数量)
                            BigDecimal taskOutbountAssit = ObjectUtil.isEmpty(taskMaterial.getWarehousedQuantityAssist()) ? BigDecimal.ZERO : taskMaterial.getWarehousedQuantityAssist();
                            taskMaterial.setWarehousedQuantityAssist(taskOutbountAssit.add(ObjectUtil.isNull(real.getAssistQuantity()) ? BigDecimal.ZERO : real.getAssistQuantity()));
                            taskMaterial.setUnwarehousedQuantityAssist(BigDecimal.ZERO);
                            taskMaterial.setWarehouseStatus("3");
                            wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
                        }
                    }
                }
                //判断任务的状态--如果任务的所有物料未入库数量都为0，则判定任务完成
                //重新获取入库任务-物料
                List<WmsInReceiptTaskMaterial> newList = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, taskId));
                int num = 0;
                for (WmsInReceiptTaskMaterial newTask : newList) {
                    if (newTask.getUnwarehousedQuantity().compareTo(BigDecimal.ZERO) == 0) {
                        num++;
                    }
                }
                if (num < newList.size()) {
                    result = false;
                }
                if (!result) {
                    task.setWarehouseStatus("2");
                } else {
                    task.setWarehouseStatus("3");
                }
                wmsInReceiptTaskMapper.updateById(task);
            }
        } else {
            throw new JeecgBootException("入库单不存在!");
        }
    }

    @Override
    public void closeTask(String id, Integer type) {
        switch (type) {
            case 1: {
                WmsInReceiptTask task = wmsInReceiptTaskMapper.selectById(id);
                if (ObjectUtil.isEmpty(task)) {
                    throw new JeecgBootException("入库任务不存在!");
                }
                if (!task.getDocumentStatus().equals("2") || task.getWarehouseStatus().equals("3")) {
                    throw new JeecgBootException("该任务不可关闭!");
                }
                task.setDocumentStatus("-1");
                wmsInReceiptTaskMapper.updateById(task);
                break;
            }
            case 2: {
                WmsOutReceiptTask task = wmsOutReceiptTaskMapper.selectById(id);
                if (ObjectUtil.isEmpty(task)) {
                    throw new JeecgBootException("出库任务不存在!");
                }
                if (!task.getDocumentStatus().equals("2") || task.getOutboundStatus().equals("3")) {
                    throw new JeecgBootException("该任务不可关闭!");
                }
                task.setDocumentStatus("-1");
                wmsOutReceiptTaskMapper.updateById(task);
                break;
            }
            case 3: {
                TakeStockPlan task = takeStockPlanMapper.selectById(id);
                if (ObjectUtil.isEmpty(task)) {
                    throw new JeecgBootException("盘点任务不存在!");
                }
                if (!task.getDocumentStatus().equals("2")) {
                    throw new JeecgBootException("该任务不可关闭!");
                }
                task.setDocumentStatus("-1");
                takeStockPlanMapper.updateById(task);
                break;
            }
            default: {
                throw new JeecgBootException("任务类型输入有误!");
            }

        }
    }

    @Override
    public IPage<WmsInReceiptTaskPageVO> listByPage(IPage<WmsInReceiptTask> pageList, WmsInReceiptTaskQueryVO param) {
        if (ObjectUtil.isNotEmpty(param.getDocumentType())) {
            List<String> documentTypeList = Arrays.asList(StringUtils.split(param.getDocumentType(), ","));
            param.setDocumentTypeList(documentTypeList);
        }
        if (ObjectUtil.isNotEmpty(param.getInWarehouseId())) {
            List<String> outWarehouseIds = Arrays.asList(StringUtils.split(param.getInWarehouseId(), ","));
            param.setInWarehouseIds(outWarehouseIds);
        }
        if (StrUtil.isNotBlank(param.getDocumentStatus())) {
            List<String> documentStatusList = Arrays.asList(StringUtils.split(param.getDocumentStatus(), ","));
            param.setDocumentStatusList(documentStatusList);
        }
        //校验角色
        setRoleAuth(param);
        return wmsInReceiptTaskMapper.getPage(pageList, param);
    }
    void setRoleAuth(WmsInReceiptTaskQueryVO param){
        //校验角色
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(Objects.isNull(sysUser)){
            param.setManageWarehouseIdList(Arrays.asList("-1"));
            param.setAdminFlag(false);
        }else if(StrUtil.contains(sysUser.getUsername(),"admin")){
            param.setManageWarehouseIdList(new ArrayList<>());
            param.setAdminFlag(true);
        }else{
            //不是管理员
            List<String> warehouseListByUserId = wmsBasicWarehouseGroupUserMapper.getWarehouseListByUserId(sysUser.getId());
            warehouseListByUserId.add("-1");
            param.setManageWarehouseIdList(warehouseListByUserId);
            param.setAdminFlag(false);
        }
    }

    @Override
    public void rawOrAuxInspect(InspectResultVO inspectResultVO) {
        log.info("原料、辅材质检-wms接收qms请求{}", inspectResultVO);
        DockDataReceiveRecord record = new DockDataReceiveRecord();
        record.setBusinessCode("in");
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        if ("raw".equals(inspectResultVO.getMaterialType())) {
            for (InspectReport reportDetail : inspectResultVO.getReportDetails()) {
                WmsInReceiptTaskMaterial one = wmsInReceiptTaskMaterialMapper.selectOne(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getSteelCoilNumber, reportDetail.getSteelCoilNum()));
                if (one == null) {
                    log.error("钢卷号:{} 未找到对应入库物料信息", reportDetail.getSteelCoilNum());
                    continue;
                }
                WmsInReceiptTaskMaterial taskMaterial = new WmsInReceiptTaskMaterial();
                taskMaterial.setId(one.getId());
                taskMaterial.setInspectResult(reportDetail.getResult());
                taskMaterial.setInspectStatus(InspectStatusEnum.INSPECTED.getName());
                taskMaterial.setInspectionMethod(inspectResultVO.getQualityMethod());
                try {
                    taskMaterial.setInspectTime(DateUtils.parseDate(inspectResultVO.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
            }
        } else if ("aux".equals(inspectResultVO.getMaterialType())) {
            for (InspectReport reportDetail : inspectResultVO.getReportDetails()) {
                WmsInReceiptTaskMaterial one = wmsInReceiptTaskMaterialMapper.selectOne(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getSaleOrderNumber, reportDetail.getSaleOrderNumber())
                        .eq(WmsInReceiptTaskMaterial::getSaleOrderLineNumber, reportDetail.getSaleOrderLineNumber()));
                if (one == null) {
                    log.error("销售订单号:{}，销售订单行号:{} 未找到对应入库物料信息", reportDetail.getSaleOrderNumber(), reportDetail.getSaleOrderLineNumber());
                    continue;
                }
                WmsInReceiptTaskMaterial taskMaterial = new WmsInReceiptTaskMaterial();
                taskMaterial.setId(one.getId());
                taskMaterial.setInspectResult(reportDetail.getResult());
                taskMaterial.setInspectStatus(InspectStatusEnum.INSPECTED.getName());
                taskMaterial.setInspectionMethod(inspectResultVO.getQualityMethod());
                try {
                    taskMaterial.setInspectTime(DateUtils.parseDate(inspectResultVO.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                wmsInReceiptTaskMaterialMapper.updateById(taskMaterial);
            }
        }

    }

    /**
     * 通过入库任务id 获取物料即时库存位置信息
     *
     * @param taskMaterialId
     * @return
     */
    @Override
    public RepertorySimpleVO getMaterialRepertoryInfoByInId(String taskMaterialId) {
        RepertorySimpleVO repertorySimpleVO = new RepertorySimpleVO();
        WmsInReceiptTaskMaterial taskMaterial = wmsInReceiptTaskMaterialMapper.selectById(taskMaterialId);
        if (!Objects.isNull(taskMaterial)) {
            //根据任务物料中的明细查询位置
            List<RepertorySimpleVO> repertoryInfoList = new ArrayList<>();
            String tempBatchCode = taskMaterial.getBatchCode();
            String tempWmsBasicMaterialId = taskMaterial.getWmsBasicMaterialId();
            if (!StrUtil.isEmpty(tempBatchCode)) {
                repertoryInfoList = wmsOutReceiptTaskMapper.getMaterialRepertoryInfo(null, tempBatchCode, taskMaterial.getWmsBasicWarehouseId(), null);
            } else {
                repertoryInfoList = wmsOutReceiptTaskMapper.getMaterialRepertoryInfo(tempWmsBasicMaterialId, null, taskMaterial.getWmsBasicWarehouseId(), taskMaterial.getWmsBasicWarehouseAreaId());
            }
            if (!CollectionUtil.isEmpty(repertoryInfoList)) {
                if (repertoryInfoList.size() > 1) {
                    throw new JeecgBootException("根据批次号、物料编码、仓库查询到多条数据，无法确定即时库存位置");
                } else {
                    repertorySimpleVO = repertoryInfoList.get(0);
                }
            }
        }
        return repertorySimpleVO;
    }

    /**
     * 当保存时获取过账状态
     *
     * @return
     */
    @Override
    public TransferStatusEnum getTransferStatusWhenSave(SimpleDocumentTypeEnum simpleDocumentType, String documentType) {
        //如果没有单据类型
        if (StrUtil.isEmpty(documentType)) {
            return TransferStatusEnum.NOT_NEED;
        }
        NeedTransferDocumentTypeEnum[] documentTypeEnums = NeedTransferDocumentTypeEnum.values();
        ArrayList<NeedTransferDocumentTypeEnum> list = ListUtil.toList(documentTypeEnums);
        List<NeedTransferDocumentTypeEnum> collect = list.stream().filter(o -> o.getCode().equals(documentType)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)) {
            return TransferStatusEnum.NOT_NEED;
        }
        NeedTransferDocumentTypeEnum needTransferDocumentType = collect.get(0);
        if (Objects.isNull(needTransferDocumentType)) {
            return TransferStatusEnum.NOT_NEED;
        } else {
            if (needTransferDocumentType.getSimpleDocumentType().equals(simpleDocumentType.getCode())) {
                return TransferStatusEnum.NOT_TRANSFER;
            } else {
                return TransferStatusEnum.NOT_NEED;
            }
        }
    }

    /**
     * 更新过账状态
     *
     * @param simpleDocumentType
     * @param taskId
     * @param receiptId
     * @param transferStatus
     */
    @Override
    public void updateTransferStatus(SimpleDocumentTypeEnum simpleDocumentType, String taskId, String receiptId, TransferStatusEnum transferStatus) {
        if (SimpleDocumentTypeEnum.IN_TASK == simpleDocumentType) {
            if (StrUtil.isEmpty(taskId)) {
                return;
            }
            this.update(new LambdaUpdateWrapper<WmsInReceiptTask>()
                    .set(WmsInReceiptTask::getTransferSapStatus, transferStatus.getCode())
                    .eq(WmsInReceiptTask::getId, taskId)
            );
        } else if (SimpleDocumentTypeEnum.IN_RECEIPT == simpleDocumentType) {
            if (StrUtil.isEmpty(receiptId)) {
                return;
            }
            wmsInReceiptService.update(new LambdaUpdateWrapper<WmsInReceipt>()
                    .set(WmsInReceipt::getTransferSapStatus, transferStatus.getCode())
                    .eq(WmsInReceipt::getId, receiptId)
            );
        } else {
            log.error("不支持的类型{}", simpleDocumentType);
        }
    }

    /**
     * 根据物料信息获取进行中的任务id
     *
     * @param wmsBasicMaterialId
     * @param batchCode
     * @return
     */
    @Override
    public List<String> getProcessTaskIdByMaterialInfo(String wmsBasicMaterialId, String batchCode) {

        List<String> taskIdList = wmsInReceiptTaskMapper.getProcessTaskIdByMaterialInfo(wmsBasicMaterialId, batchCode);
        return taskIdList;
    }

    @Override
    public Result<Void> lightIBSHandleInbound(LightRequestHandleInboundVO vo) {
        WmsInReceiptTaskMaterial detail = wmsInReceiptTaskMaterialMapper.selectById(vo.getWmsInReceiptTaskMaterialId());
        WmsInReceiptTask task = this.getById(detail.getWmsInReceiptTaskId());
        if (ArrayUtil.contains(needHandleLight,task.getDocumentType())){
            if (StrUtil.isBlank(vo.getWmsBasicWarehouseAreaLocationId())){
                return Result.OK("库位为空");
            }
            if (StrUtil.isBlank(detail.getBatchCode())){
                return Result.OK("批次号为空");
            }
            WmsLightConfig lightConfig = iWmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                    .eq(WmsLightConfig::getWmsBasicWarehouseId, vo.getWmsBasicWarehouseId())
                    .eq(WmsLightConfig::getWmsBasicWarehouseAreaId, vo.getWmsBasicWarehouseAreaId())
                    .eq(WmsLightConfig::getWmsBasicWarehouseAreaLocationId, vo.getWmsBasicWarehouseAreaLocationId())
                    .last("limit 1")
            );
            if (lightConfig == null){
                return Result.OK("对应位置下没有安灯配置");
            }
            //如果在灭灯的时候,同入库任务中有相同库位的其他批次号,则提示XX库位存在相同建议库位的批次号XXX,不灭灯
            if (vo.getState() == 0){
                //collect: 左边列表的数量
                List<LightRequestHandleInboundLocationVO> collect = vo.getList().stream().filter(
                        s -> Objects.equals(s.getWmsBasicWarehouseId(), vo.getWmsBasicWarehouseId()) &&
                                Objects.equals(s.getWmsBasicWarehouseAreaId(), vo.getWmsBasicWarehouseAreaId()) &&
                                Objects.equals(s.getWmsBasicWarehouseAreaLocationId(), vo.getWmsBasicWarehouseAreaLocationId())
                ).collect(Collectors.toList());
                //如果相同库位,扫过去一个,右边还有一个,再扫库位码此时扫库位码会灭灯,希望不灭灯
                //查询相同库位的在该任务下有几条
                List<WmsInReceiptTaskMaterial> sameLocationMaterialList = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .eq(WmsInReceiptTaskMaterial::getWmsBasicWarehouseId, vo.getWmsBasicWarehouseId())
                        .eq(WmsInReceiptTaskMaterial::getWmsBasicWarehouseAreaId, vo.getWmsBasicWarehouseAreaId())
                        .eq(WmsInReceiptTaskMaterial::getWmsBasicWarehouseAreaLocationId, vo.getWmsBasicWarehouseAreaLocationId())
                );
                //左边的数量小于总数量,说明还有未扫过去的,此时不灭灯
                if (CollectionUtil.isNotEmpty(collect)&&CollectionUtil.isNotEmpty(sameLocationMaterialList)){
                    if (collect.size()<sameLocationMaterialList.size()){
                        return Result.OK("相同位置有未扫描的,不灭灯");
                    }
                }
                //如果相同库位,扫过去两个,再删除或者扫描库位码的时候此时扫库位码会灭灯,希望不灭灯
                if (CollectionUtil.isNotEmpty(vo.getList())){
                    if (CollectionUtil.isNotEmpty(collect) && collect.size() >1){
                        List<WmsInReceiptTaskMaterial> materials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                                .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, detail.getWmsInReceiptTaskId())
                                .ne(WmsInReceiptTaskMaterial::getBatchCode, detail.getBatchCode())
                                .eq(WmsInReceiptTaskMaterial::getWmsBasicWarehouseId, vo.getWmsBasicWarehouseId())
                                .eq(WmsInReceiptTaskMaterial::getWmsBasicWarehouseAreaId, vo.getWmsBasicWarehouseAreaId())
                                .eq(WmsInReceiptTaskMaterial::getWmsBasicWarehouseAreaLocationId, vo.getWmsBasicWarehouseAreaLocationId())
                        );
                        if (CollectionUtil.isNotEmpty(materials)){
                            WmsBasicWarehouseAreaLocation areaLocation = iWmsBasicWarehouseAreaLocationService.getById(materials.get(0).getWmsBasicWarehouseAreaLocationId());
                            String str = "";
                            if (areaLocation != null){
                                str = str + areaLocation.getName();
                            }
                            return Result.OK(str+"存在相同建议库位的批次号"+materials.get(0).getBatchCode()+",不灭灯");
                        }
                    }
                }
            }
            List<LightRequestVO> reqVO = new ArrayList<>();
            LightRequestVO lightRequestVO = new LightRequestVO();
            lightRequestVO.setLocationId(lightConfig.getLocationId()+"-"+lightConfig.getSiteCode());
            lightRequestVO.setState(vo.getState());
            //先写死黄色,后面根据配置来
            lightRequestVO.setLightColor(128);
            reqVO.add(lightRequestVO);
            int lightIBS = 0;
            if("simulate".equals(lightMode)){
                lightIBS = 1;
            }else {
                try {
                    lightIBS = lightIBSDockingService.lightIBS(reqVO);
                }catch (Exception e){
                    log.error("调用安灯失败{}",e.getMessage());
                }
            }
            //查询wms_light_config确认是否开启成功
//            WmsLightConfig wmsLightConfig = iWmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
//                    .eq(WmsLightConfig::getLocationId, lightConfig.getLocationId())
//                    .eq(WmsLightConfig::getSiteCode,lightConfig.getSiteCode())
//                    .last("limit 1")
//            );
            //ibs返回0表示失败
            if (lightIBS == 0){
                return Result.OK(vo.getState() == 0 ? "关灯失败 " : "开灯失败 ");
            }
            //如果是开灯成功之后往WmsTaskMaterialLight表插入数据
            if (vo.getState() == 1){
                //先看有无对应的数据,否则连续开灯会导致多条数据存在
                List<WmsTaskMaterialLight> list = iWmsTaskMaterialLightService.list(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                        .eq(WmsTaskMaterialLight::getTaskId, detail.getWmsInReceiptTaskId())
                        .eq(WmsTaskMaterialLight::getTaskMaterialId, detail.getId())
                );
                if (CollectionUtil.isNotEmpty(list)){
                    String[] ignore = {"id","createTime","createBy","updateBy","updateTime"};
                    WmsTaskMaterialLight materialLight = BeanUtil.copyProperties(detail,WmsTaskMaterialLight.class,ignore);
                    materialLight.setTaskId(detail.getWmsInReceiptTaskId());
                    materialLight.setTaskMaterialId(detail.getId());
                    materialLight.setSimpleDocumentStatus(SimpleDocumentTypeEnum.IN_TASK.getCode());
                    materialLight.setLightStatus(LightStateEnum.BRIGHT.getCode()+"");
                    iWmsTaskMaterialLightService.save(materialLight);
                }
            }else {
                //关灯成功之后删除对应的数据
                iWmsTaskMaterialLightService.remove(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                        .eq(WmsTaskMaterialLight::getWmsBasicWarehouseId, vo.getWmsBasicWarehouseId())
                        .eq(WmsTaskMaterialLight::getWmsBasicWarehouseAreaId, vo.getWmsBasicWarehouseAreaId())
                        .eq(WmsTaskMaterialLight::getWmsBasicWarehouseAreaLocationId, vo.getWmsBasicWarehouseAreaLocationId())
                );
            }
            return Result.ok(vo.getState()==0 ? "关灯成功" : "开灯成功");
        }
        return Result.ok("任务不在指定范围,无需操作");
    }

    @Override
    public Result<Void> lightIBSHandleInboundAll(LightRequestHandleInboundAllVO vo) {
        WmsInReceiptTask task = this.getById(vo.getTaskId());
        List<WmsInReceiptTaskMaterial> taskMaterials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId,vo.getTaskId())
        );
        taskMaterials = taskMaterials.stream()
                .filter(s->StrUtil.isNotBlank(s.getBatchCode())&&StrUtil.isNotBlank(s.getWmsBasicWarehouseAreaLocationId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isEmpty(taskMaterials)){
            return Result.ok("没有符合关灯条件的明细");
        }
        if (ArrayUtil.contains(needHandleLight,task.getDocumentType())){
            List<LightRequestVO> reqVO = new ArrayList<>();
            taskMaterials.forEach(one->{
                WmsLightConfig lightConfig = iWmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                        .eq(WmsLightConfig::getWmsBasicWarehouseId, one.getWmsBasicWarehouseId())
                        .eq(WmsLightConfig::getWmsBasicWarehouseAreaId, one.getWmsBasicWarehouseAreaId())
                        .eq(WmsLightConfig::getWmsBasicWarehouseAreaLocationId, one.getWmsBasicWarehouseAreaLocationId())
                        .last("limit 1")
                );
                if (lightConfig != null){
                    LightRequestVO lightRequestVO = new LightRequestVO();
                    lightRequestVO.setLocationId(lightConfig.getLocationId()+"-"+lightConfig.getSiteCode());
                    lightRequestVO.setState(vo.getState());
                    //先写死黄色,后面根据配置来
                    lightRequestVO.setLightColor(128);
                    reqVO.add(lightRequestVO);
                }
            });
            if (CollectionUtil.isEmpty(reqVO)){
                return Result.ok("明细下没有可用的安灯配置");
            }
            int lightIBS = 0;
            if("simulate".equals(lightMode)){
                lightIBS = 1;
            }else {
                try {
                    lightIBS = lightIBSDockingService.lightIBS(reqVO);
                }catch (Exception e){
                    log.error("调用安灯失败{}",e.getMessage());
                }
            }
            //ibs返回0表示失败
            if (lightIBS == 0){
                return Result.OK(vo.getState() == 0 ? "全部关灯失败 " : "全部开灯失败 ");
            }
            if (vo.getState() == 1){
                List<WmsTaskMaterialLight> list = new ArrayList<>();
                taskMaterials.forEach(detail->{
                    //如果是开灯成功之后往WmsTaskMaterialLight表插入数据
                        //先看有无对应的数据,否则连续开灯会导致多条数据存在
                    List<WmsTaskMaterialLight> lights = iWmsTaskMaterialLightService.list(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                            .eq(WmsTaskMaterialLight::getTaskId, detail.getWmsInReceiptTaskId())
                            .eq(WmsTaskMaterialLight::getTaskMaterialId, detail.getId())
                    );
                    if (CollectionUtil.isNotEmpty(lights)){
                            String[] ignore = {"id","createTime","createBy","updateBy","updateTime"};
                            WmsTaskMaterialLight materialLight = BeanUtil.copyProperties(detail,WmsTaskMaterialLight.class,ignore);
                            materialLight.setTaskId(detail.getWmsInReceiptTaskId());
                            materialLight.setTaskMaterialId(detail.getId());
                            materialLight.setSimpleDocumentStatus(SimpleDocumentTypeEnum.IN_TASK.getCode());
                            materialLight.setLightStatus(LightStateEnum.BRIGHT.getCode()+"");
                            list.add(materialLight);
                        }
                });
                iWmsTaskMaterialLightService.saveBatch(list);
            }else {
                taskMaterials.forEach(detail->{
                    //关灯成功之后删除对应的数据
                    iWmsTaskMaterialLightService.remove(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                            .eq(WmsTaskMaterialLight::getWmsBasicWarehouseId, detail.getWmsBasicWarehouseId())
                            .eq(WmsTaskMaterialLight::getWmsBasicWarehouseAreaId, detail.getWmsBasicWarehouseAreaId())
                            .eq(WmsTaskMaterialLight::getWmsBasicWarehouseAreaLocationId, detail.getWmsBasicWarehouseAreaLocationId())
                    );
                });
            }
            return Result.ok(vo.getState()==0 ? "全部关灯成功" : "全部开灯成功");
        }
        return Result.ok("任务不在指定范围,无需操作");
    }
}
